import Orders from '@/components/Orders';
import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Checkbox, Dialog, Drawer, Message } from '@alifd/next';
import { t } from '@lingui/macro';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useRef, useState } from 'react';
import { useHistory } from 'react-router';
import ScPriceForm from './components/ScPriceForm';
import { column } from './stores/definitions';
import ScShits from './components/ScShifts';

function ScPrice() {
  const [args, setArgs] = useState({ priceType: 2 });
  const [showOrders, setShowOrders] = useState(false);
  const { scPriceStore: store } = useStore();
  const [modal, setModal] = useState([]);
  const [dup, setDup] = useState([]);
  const curRef = useRef(); // table中的选中行
  const history = useHistory();

  const [counts, setCounts] = useState([]);
  const [shareCounts, setShareCounts] = useState([]);
  const [selfCounts, setSelfCounts] = useState([]);

  useEffect(() => {
    (async () => {
      const share = await fetchShareCounts();
      const self = await fetchSelfCounts();
      setShareCounts(share);
      setSelfCounts(self);
    })();
  }, [store.data]);

  useEffect(() => {
    if (showOrders) {
      (async () => {
        const res = await fetchOrderCounts();
        setCounts(res);
      })();
    } else {
      setCounts([]);
    }
  }, [showOrders, store.data]);

  async function fetchOrderCounts() {
    const promiseAry = store.data.map((p) => store.api.orderCount({
      search: {
        startMainArea: p.startMainArea,
        startMinorAreas: p.startMinorAreas,
        endMainArea: p.endMainArea,
        endMinorAreas: p.endMinorAreas,
      },
    }).then((r) => ({ id: p.id, count: r })));
    return Promise.all(promiseAry);
  }

  async function fetchShareCounts() {
    const newPrices = await store.data.map(async (item) => await store.api.shiftsCount({
      findTypes: [
        2,
      ],
      routePriceId: item.id,
      history: 0,
    }).then((res) => ({
      id: item.id,
      shareCount: res,
    })));
    return Promise.all(newPrices);
  }

  async function fetchSelfCounts() {
    const newPrices = await store.data.map(async (item) => await store.api.shiftsCount({
      findTypes: [
        1,
      ],
      routePriceId: item.id,
      history: 0,
    }).then((res) => ({
      id: item.id,
      shareCount: res,
    })));
    return Promise.all(newPrices);
  }

  // eslint-disable-next-line no-unused-vars
  async function fetchShifts() {
    const promiseAry = store.data.map((p) => store.api.shifts(p.id)
      .then((r) => {
        // eslint-disable-next-line no-param-reassign
        p.shift = r;
      }));
    return Promise.all(promiseAry);
  }

  useEffect(() => {
    store.search = args;
  }, [args]);

  const handleSearch = (params) => {
    const { startArea: _, endArea: __, ...searchArgs } = params.values;
    const { startArea, endArea } = params.valueObjects;
    const arg1 = {
      startMainArea: startArea?.selectedPath?.[0]?.value,
      startMinorAreas: startArea?.selectedPath?.length > 1 ? [startArea?.selectedPath?.[1].id] : [],
      endMainArea: endArea?.selectedPath?.[0]?.value,
      endMinorAreas: endArea?.selectedPath?.length > 1 ? [endArea?.selectedPath?.[1].id] : [],
    };

    setArgs({
      ...args,
      ...arg1,
      ...searchArgs,
    });
  };

  // 点击打开订单查看
  const handleOpenOrder = (price) => {
    curRef.current = price;
    setModal(['viewOrder']);
  };

  // 点击查看班次
  const handleOpenShifts = (price, type) => {
    curRef.current = price;
    setModal([type === 'share' ? 'viewShareShifts' : 'viewShifts']);
  };

  // 点击打开添加
  const handleOpenAdd = () => {
    curRef.current = {};
    setModal(['add']);
  };

  // 点击打开编辑
  const handleOpenEdit = (price) => {
    curRef.current = price;
    setModal(['edit']);
  };

  // Modal窗口关闭回调
  const handleCancel = () => {
    setModal([]);
  };

  const handleRelevancy = () => {
    history.push('/price/sc/create/relevancy');
  };

  // 变更数据提交
  const handleUpdate = async (price) => {
    const exists = await store.exitingLines(price);
    if (exists.length > 0 && exists[0].startMain) {
      setDup(exists);
      return;
    }

    if (!_.isEmpty(price)) {
      try {
        const { startMinorAreas, endMinorAreas } = toJS(price);
        await store.update({ ...toJS(price), startMinorAreas: [startMinorAreas], endMinorAreas: [endMinorAreas] });
        Message.success({ content: t`修政成功` });
      } catch (e) {
        Message.error({ content: t`修政失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  // 新增订单数据提交
  const handleCreate = async (price) => {
    const exists = await store.exitingLines(price);
    if (exists.length > 0 && exists[0].startMain) {
      setDup(exists);
      return;
    }

    if (!_.isEmpty(price)) {
      try {
        const { startMinorAreas, endMinorAreas } = toJS(price);
        await store.create({ ...toJS(price), startMinorAreas: [startMinorAreas], endMinorAreas: [endMinorAreas] });
        Message.success({ content: t`创建成功` });
      } catch (e) {
        Message.error({ content: t`创建失败`, duration: 7000 });
        throw e;
      }
    }
    setModal([]);
  };

  const handleDelete = (price) => {
    Dialog.confirm({
      content: t`确认删除该线路吗？`,
      onOk: async () => {
        try {
          await store.remove(toJS(price));
          Message.success({ content: t`删除成功` });
        } catch (e) {
          Message.error({ content: t`删除失败`, duration: 7000 });
          throw e;
        }
      },
    });
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        className="action-panel"
        onSearch={handleSearch}
        actions={[
          {
            name: 'btn-addPrice',
            title: t`添加线路`,
            type: 'primary',
            onClick: () => handleOpenAdd(),
          },
          {
            name: 'btn-relevancy',
            title: t`线路关联配置`,
            type: 'primary',
            onClick: () => handleRelevancy(),
          },
        ]}
        searchItems={[
          {
            name: 'startArea',
            type: 'sc-station',
            props: {
              placeholder: t`始发城市/区域`,
              changeOnSelect: true,
              maxLevel: 3,
              isFilterDisabled: true,
            },
          },
          {
            name: 'endArea',
            type: 'sc-station',
            props: {
              placeholder: t`到达城市/区域`,
              changeOnSelect: true,
              maxLevel: 3,
              isFilterDisabled: true,
            },
          },
        ]}
        extraItems={[
          {
            name: 'cbx-showOrders',
            component: <Checkbox style={{ marginLeft: 10 }} onChange={(v) => setShowOrders(v)}>{t`查看订单`}</Checkbox>,
          },
        ]}
      />
      <div className="content">
        <TauTable
          primaryKey="itemId"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          sort={store.tableSort}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('beginAreaName', {}),
            column('endAreaName', {}),
            column('shareShift', {
              width: 88,
              cell: (v, _, price) => {
                const findIdx = shareCounts.find((item) => item.id === price.id);
                return <Button onClick={() => history.push(`/price/sc/${price.id}/share`)} type="primary" text>{findIdx?.shareCount !== 0 ? t`班次数量${findIdx?.shareCount}` : t`未设置班次`}</Button>;
              },
            }),
            column('shift', { width: 88, cell: (v, _, price) => <Button onClick={() => handleOpenShifts(price, 'general')} type="primary" text>{t`查看班次`}</Button> }),
            column('selfShift', {
              width: 88,
              cell: (v, _, price) => {
                const findIdx = selfCounts.find((item) => item.id === price.id);
                return <Button onClick={() => history.push(`/price/sc/${price.id}/self`)} type="primary" text>{findIdx?.shareCount !== 0 ? t`班次数量${findIdx?.shareCount}` : t`未设置班次`}</Button>;
              },
            }),
            column('state', { width: 88 }),
            { dataIndex: 'orderCount', title: t`订单`, width: 80, cell: (_, __, price) => <Button onClick={() => handleOpenOrder(price)} type="primary" text>{counts.find((c) => c.id === price.id)?.count || 0}</Button> },
            {
              title: t`操作`,
              dataIndex: 'id',
              width: 100,
              cell: (_, __, price) => (
                <>
                  <Button text type="primary" onClick={() => handleOpenEdit(price)} >{t`编辑`}</Button>
                  <span style={{ color: 'var(--btn-text-primary-color, #5584FF)' }}> | </span>
                  <Button text type="primary" style={{ color: 'red' }} onClick={() => handleDelete(price)} >{t`删除`}</Button>
                </>),
            },

          ].filter((c) => c.dataIndex !== 'orderCount' || showOrders)}
        />
      </div>
      <Drawer
        visible={modal[0] === 'viewOrder'}
        title={t`查看订单`}
        onClose={() => setModal([])}
        closeMode={['esc', 'mask', 'close']}
        style={{ maxWidth: '90%' }}
        width="90%"
      >
        <Orders
          orderType={2}
          hideActions
          hiddenSearchItems={['startStations', 'endStations', 'portType']}
          filter={_.pick(curRef.current, ['priceType', 'startMainArea', 'startMinorAreas', 'endMainArea', 'endMinorAreas', 'portTypes'])}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'add' || modal[0] === 'edit'}
        title={modal[0] === 'add' ? t`添加线路价格` : t`修改线路价格`}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal([...modal, `toClose$${Date.now()}`])}
        width="90%"
      >
        <ScPriceForm
          priceId={curRef.current?.id}
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal[0] === 'add' ? handleCreate : handleUpdate}
        />
      </Drawer>
      <Drawer
        visible={modal[0] === 'viewShifts'}
        title={<span>{t`班次`} <span style={{ color: 'grey', fontWeight: 400, marginLeft: 20 }}>{curRef.current?.beginAreaName} {'-->'} {curRef.current?.endAreaName}</span></span>}
        onClose={() => setModal([])}
        closeMode={['esc', 'mask', 'close']}
        style={{ maxWidth: '70%' }}
        width="90%"
      >
        <ScShits price={curRef.current} />
      </Drawer>
      <Dialog
        v2
        title={t`存在重复的线路`}
        centered
        width="50%"
        height="70vh"
        onOk={() => setDup([])}
        onClose={() => setDup([])}
        visible={dup.length}
        footerActions={['ok']}
      >
        <div style={{ display: 'flex', flexDirection: 'column', alignItems: 'flex-start' }}>
          {/* <span>{t`重复的线路:`}</span> */}
          {dup.map((v) => <span>{`${v.startMainText}-${v.startMinorText} ---> ${v.endMainText}-${v.endMinorText}`}</span>)}
        </div>
      </Dialog>
    </TauPage>
  );
}

export default observer(ScPrice);
